package idv.arthur.work;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ManipulateGridPersonnel extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public ManipulateGridPersonnel() {
        super();
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	doPost(request,response);
    }

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		Widgets wid = new Widgets();
		request.setCharacterEncoding( wid.UIcodeSet );
		response.setContentType("application/text");
		response.setCharacterEncoding( wid.UIcodeSet );
		
		Connection conn = wid.getConn(true);
		PreparedStatement ps = null;
		ResultSet rs = null;
		String errPars = "}";
		
		String strSQL = "";
		String oper = request.getParameter("oper");
		String id = "";
		String result = "";
		final String currentUser = request.getParameter("loginUser");
		String roleList = request.getParameter("roleList");
		
		try {
			/** 判別需進行何種操作 **/
			if ( "del".equalsIgnoreCase(oper) ) {
				id = request.getParameter("id");
				strSQL = "DELETE FROM personnel WHERE userid=?";
				ps = conn.prepareStatement(strSQL);
				ps.setString(1, id);
				ps.execute();
				
				wid.keepLogProfile(wid.PERSONNEL, wid.DELETE, currentUser, conn, ps);
				result = "刪除了"+id;
				
			} else if ( "add".equalsIgnoreCase(oper) ) {
				strSQL = "SELECT COUNT(userid) FROM personnel WHERE userid=?";
				id = request.getParameter("userid");
				ps = conn.prepareStatement(strSQL);
				ps.setString(1, id);
				rs = ps.executeQuery();
				rs.next();
				if ( rs.getInt(1) == 0 ) {		//測試此ID 是否已存在
					strSQL = "INSERT INTO personnel (userid,username,email,creator,createdDateTime,phonenum,pwd) VALUES (?,?,?,?,?,?,?)";
					ps = conn.prepareStatement(strSQL);
					ps.setString(1, id);
					ps.setString(2, wid.UI2DB( request.getParameter("username"),conn.getMetaData().getDatabaseProductName() ) );
					ps.setString(3, request.getParameter("email"));
					ps.setString(4, currentUser);
					ps.setTimestamp(5, wid.currentTimeStamp());
					ps.setString(6, request.getParameter("phonenum"));
					ps.setString(7, request.getParameter("pwd"));
					ps.execute();
					
					if ( roleList != null ) {
						String[]  roleArr = roleList.split("(");
						strSQL = "INSERT INTO mproleuser (userId,roleId) VALUES (?,?)";
						ps = conn.prepareStatement(strSQL);
						ps.setString(1, id);
						for (int i=1; i<roleArr.length;i++) {
							ps.setString(2, roleArr[i].substring(0, 1));
							ps.execute();
						}
					}
					
					wid.keepLogProfile(wid.PERSONNEL, wid.ADD, currentUser, conn, ps);
					result = "新增完成 "+id;
				} else {
					result = id+" 已存在 !";		
				}
			} else if ( "edit".equalsIgnoreCase(oper) ) {
				strSQL = "UPDATE personnel SET username=?,email=?,phonenum=?,pwd=?,lastUpdator=?,lastUpdatedDateTime=? WHERE userid=?";
				id = request.getParameter("userid");
				ps = conn.prepareStatement(strSQL);
				ps.setString(1, wid.UI2DB( request.getParameter("username"),conn.getMetaData().getDatabaseProductName() ) );
				ps.setString(2, request.getParameter("email"));
				ps.setString(3, request.getParameter("phonenum"));
				ps.setString(4, request.getParameter("pwd"));
				ps.setString(5, currentUser);
				ps.setTimestamp(6, wid.currentTimeStamp());
				ps.setString(7, id);
				ps.execute();
				 
				if ( roleList != null ) {
					roleList = roleList.replace("(", "_");
					String[]  roleArr = roleList.split("_");
					strSQL = "DELETE FROM mproleuser WHERE userId=?";
					ps = conn.prepareStatement(strSQL);
					ps.setString(1, id);
					ps.execute();
					strSQL = "INSERT INTO mproleuser (userId,roleId) VALUES (?,?)";
					ps = conn.prepareStatement(strSQL);
					ps.setString(1, id);
					for (int i=1; i<roleArr.length;i++) {
						ps.setString(2, roleArr[i].substring(0, 1));
						ps.execute();
					}
				}
				wid.keepLogProfile(wid.PERSONNEL, wid.UPDATE, currentUser, conn, ps);
				result = "修改完成 "+id;
				
			}
		} catch (SQLException e) {
			result = "異動"+id+"失敗!!\n\n";
			result += wid.errProcess(e);
			wid.kem(conn, ps, e, wid.toEType("SQLException")+errPars, wid.isPrint2Console );
		} catch (UnsupportedEncodingException e) {
			result = "異動"+id+"失敗!!\n\n";
			result += wid.errProcess(e);
			wid.kem(conn, ps, e, wid.toEType("UnsupportedEncodingException")+errPars, wid.isPrint2Console );
		} catch (Exception e) {
			result = "異動"+id+"失敗!!\n\n";
			result += wid.errProcess(e);
			wid.kem(conn, ps, e, wid.toEType("Exception")+errPars, wid.isPrint2Console );
		} finally {
			try {
				if (rs!= null) {rs.close();}
				if (ps!= null) {ps.close();}
				if (conn!= null) {conn.close();}
			} catch (SQLException e) {
				System.out.println(wid.errProcess(e));
			}
		}

		
		
		response.getWriter().write(result);		
	}
}